
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;

import com.facebook.api.*;
import com.facebook.api.schema.FriendsGetResponse;
import com.facebook.api.schema.UsersGetInfoResponse;

/**
 * Servlet implementation class for Servlet: BaffesServlet
 *
 */
 public class BaffesServlet extends FacebookServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   private Database db;
   FacebookRestClient fbrclient;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public BaffesServlet() {
		super();
		db = new Database("com.mysql.jdbc.Driver");
		db.open("jdbc:mysql://mysql.alwaysdata.com/gestionprojet_facebook","gestionprojet", "polytech");

	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("BaffesServlet");
		String[] uids;
				
		fbrclient = getAuthenticatedFacebookClient(request, response);
		if(fbrclient == null)
			return;
				
		
		uids = (String[])request.getParameterValues( "ids" );
		
		if(uids != null){
			//Recuperation ID user courant
	
			try {
				long myID = fbrclient.users_getLoggedInUser();
				envoyerBaffes(uids,myID);
			} catch (FacebookException e1) {
				e1.printStackTrace();
			}			
			
			request.getRequestDispatcher("HomeServlet").forward(request, response);
		}else{		
			getUserInfos(request, fbrclient);
			request.setAttribute("FB_APP_URL", FacebookServlet.FB_APP_URL);
			request.setAttribute("FB_API_KEY", FacebookServlet.FB_API_KEY);
			request.setAttribute("FB_APP_NAME", FacebookServlet.FB_APP_NAME);
			request.setAttribute("FB_SERVER_URL", FacebookServlet.FB_SERVER_URL);
			request.getRequestDispatcher("sendBaffes.jsp").forward(request, response);
		}
	}
	
	private void envoyerBaffes(String[] uids, long myID){
		
		String struids = "";
		ArrayList<Long> luids = new ArrayList<Long>();
		
		System.out.println(uids);
		
		for(int i =0; i < uids.length ; i++){
			//ajouter les ids dans la table
			envoyerSQLBaffe(myID,Long.parseLong(uids[i]));
							
			struids += uids[i] + ",";
			luids.add(Long.parseLong(uids[i]));
		}
		struids = struids.substring(0, struids.length() - 1);
					
		
	    TemplatizedAction action = new TemplatizedAction("{actor} a mis une baffe à {target}");                      //the user has recommended a book
	    action.addTargetIds(struids);
	    action.setBodyTemplate("{actor} utilise Fous Des Baffes!");                                               //set a body template (optional)
	    action.setBodyGeneral("Toi aussi tu veux mettre des claques a tes amis? <br/> <a href='http://apps.facebook.com/fousdesbaffes'>Fous Des Baffes</a>");                                     //set general body content (optional)
	    action.addPicture("http://www.la-compagnie-des-elfes.com/catalog/images/main%20perfo.jpg", "http://apps.facebook.com/fousdesbaffes");    //add up to 4 pictures (optional)
	    	
	    try {
	    	//publier feed
			fbrclient.feed_PublishTemplatizedAction(action); //publish to feed
			
			//envoyer notification
			fbrclient.notifications_send(luids, "viens de te mettre une baffe");
			System.out.println("Myid="+myID );
			fbrclient.notifications_sendFbmlEmail(luids, "Tu t'es pris une baffe", "<fb:name uid="+myID+" /> viens de te mettre une baffe");
	
		} catch (FacebookException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	private void envoyerSQLBaffe(long idE, long idR){
		String requete = "INSERT into baffes VALUES(NULL, " + idE + ", " + idR + ", now())";
		db.executeUpdate(requete);
	}
	
	private void getUserInfos(HttpServletRequest request,FacebookRestClient fbrclient) {
	
		try {
			long myID = fbrclient.users_getLoggedInUser();

			EnumSet<ProfileField> fields = EnumSet.of(
					com.facebook.api.ProfileField.NAME,
					com.facebook.api.ProfileField.PIC,
					com.facebook.api.ProfileField.PIC_SQUARE);

			ArrayList<Long> users = new ArrayList<Long>();
			
			// add my friends ids

			fbrclient.friends_get();
			FriendsGetResponse friendsResp = (FriendsGetResponse) fbrclient.getResponsePOJO();
			List<Long> friends = friendsResp.getUid();
			int nbFriends = friends.size();
			for(int i=0;i<nbFriends;i++){
				users.add(friends.get(i));
			}
			
			//System.out.println(users);

			// recuperation des informations
			fbrclient.users_getInfo(users, fields);
			UsersGetInfoResponse usersInfo = (UsersGetInfoResponse) fbrclient.getResponsePOJO();
			
			System.out.println("Nombre d'amis : " + usersInfo.getUser().size());
			
			request.setAttribute("users", usersInfo.getUser());
			request.setAttribute("myID", myID);

			request.setAttribute("nbFriends", nbFriends);
		} catch (FacebookException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}

	}
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}   	  	    
}